package com.mazaiting.api.decoder;

import com.alibaba.fastjson.JSON;
import com.mazaiting.common.core.domain.result.Result;
import com.mazaiting.common.core.ex.runtime.FeignBizException;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.Objects;

/**
 * 自定义异常处理
 */
@Slf4j
public class CustomizeErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        Exception exception = null;
        try {
            // 获取原始的返回内容
            String json = Util.toString(response.body().asReader(Charset.defaultCharset()));
            log.error("远程调用异常: " + json);
            // 将返回内容反序列化为Result，这里应根据自身项目作修改
            Result<?> result = JSON.parseObject(json, Result.class);
            // 业务异常抛出简单的 RuntimeException，保留原来错误信息
            if (Objects.isNull(result)) {
                throw FeignException.errorStatus(methodKey, response);
            }
            if (!result.check()) {
                exception  = new FeignBizException(result);
            }
        } catch (Exception ex) {
            log.error("远程调用异常处理异常: ", ex);
            exception = FeignException.errorStatus(methodKey, response);
        }
        return exception;
    }
}